#!/usr/bin/perl -w
use strict;

use FindBin;
use lib ("$FindBin::Bin/..", "/net/cpp-group/Leo/bin");
my ($cmd);
use db_parameters;
use ensembl_parameters;


print STDERR <<"HEADLINE";
888888888888888888888888888888888888888888888888888888888888888888888

    table_interpro_data

	Description:
		Obtain ENSEMBL InterPro data from sanger database
	Populates DB tables:
		domains.interpro_data

888888888888888888888888888888888888888888888888888888888888888888888

HEADLINE

#_________________________________________________________________________________________

#	retrieve_ensembl_loci

#		retrieve data from ENSEMBL

#_________________________________________________________________________________________
sub retrieve_ensembl_interpro_data($\%)
{
	my ($taxon, $interpro_data) = @_;
	return unless ($taxon->[ALT_SOURCE] eq '.');

	#
	#	Connect to ensembl
	#
	my $ens_db_name = $taxon->[ENS_TAXON] .'_core_'.$taxon->[ENS_VERSION];
	my $dbh = DBI->connect("dbi:mysql:$ens_db_name:$ens_db_host", "$ens_db_user", '',
							{
								RaiseError => 1,
								AutoCommit => 1,
								PrintError => 0
							}
						)
	or die "Database connection not made: DBI::errstr()";

	#
	#	Get InterPro descriptions
	#
	my $array = $dbh->selectall_arrayref(<<'PL/SQLCMD');
	SELECT
		DISTINCT (interpro_ac)
		interpro_ac,
		display_label,
		description
	FROM
		interpro i,
		xref x
	WHERE i.interpro_ac = x.dbprimary_acc;
PL/SQLCMD


	#
	#	Save in hash to avoid redundancy across species
	#
	for my $data (@$array)
	{
		$data->[0] =~ tr/\t\n/  /;
		$data->[1] =~ tr/\t\n/  /;
		$data->[2] =~ tr/\t\n/  /;
		$interpro_data->{$data->[0]} = "$data->[0]\t$data->[1]\t$data->[2]\n";
	}

}


#
#	Get DB parameters
#
my @db_param = get_ensembl_taxon_data();
my $dbh = connect_to_panda();
$dbh->do("TRUNCATE TABLE domains.interpro_data;");

my %interpro_data;

#
#	Retrieving InterPro data for each taxon from Ensembl
#
for my $taxon_data(@db_param)
{
	print STDERR "\tObtaining InterPro descriptions from Ensemble for ".$taxon_data->[TAXON]."\n";
	retrieve_ensembl_interpro_data($taxon_data, %interpro_data);
}


#
#	Put InterPro data into panda
#
print STDERR "\tCopying descriptions for ", scalar keys %interpro_data, " InterPro domains to panda\n";
$dbh->do("TRUNCATE domains.interpro_data;");
$dbh->do("COPY domains.interpro_data(interpro_ac, interpro_name,  interpro_description) FROM STDIN");
for (values %interpro_data)
{
	$dbh->func($_, 'putline');
}
$dbh->func("\\.\n", 'putline');
$dbh->func('endcopy');
$dbh->disconnect;
print STDERR "\tCompleted\n";
